package org.btik.light.mobile.ui.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import org.btik.light.mobile.R;

/**
 * @author lustre
 * @since 2023/4/14 0:17
 */
public class YAxisSpeedJoystickView extends View implements View.OnTouchListener {

    private final Paint borderPaint = new Paint();

    private final Paint silderPaint = new Paint();

    private float width = 100;

    private float height = 220;

    private float sliderWidth = width;

    private float sliderHeight = sliderWidth;

    /**
     * 滑块可以滑动的区间起始 中点的y坐标
     */
    private float availableStart = sliderHeight / 2;

    /**
     * 滑块可以滑动的区间结束 中点的y坐标
     */
    private float availableEnd = height - sliderHeight / 2;

    private float rangeWidth = availableEnd - availableStart;

    private RectF border;

    private RectF slider;

    private float yOffSet = 0;

    private volatile int value;

    private ValueAnimator positionAnimator; //自动回到底部的动画

    private OnValueChangeListener onValueChangeListener;

    private OnValueResetListener onValueResetListener;

    public YAxisSpeedJoystickView(Context context) {
        super(context);
        init(context, null);
    }

    public YAxisSpeedJoystickView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public YAxisSpeedJoystickView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, @Nullable AttributeSet attrs) {
        if (attrs != null) {
            try (TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.YAxisSpeedJoystickView)) {
                int borderColor = typedArray.getColor(R.styleable.YAxisSpeedJoystickView_borderColor, Color.GRAY);
                width = typedArray.getDimension(R.styleable.YAxisSpeedJoystickView_borderWidth, 100);
                height = typedArray.getDimension(R.styleable.YAxisSpeedJoystickView_borderHeight, 220);
                int sliderColor = typedArray.getColor(R.styleable.YAxisSpeedJoystickView_sliderColor, Color.LTGRAY);
                sliderWidth = typedArray.getDimension(R.styleable.YAxisSpeedJoystickView_sliderWidth, width);
                sliderHeight = typedArray.getDimension(R.styleable.YAxisSpeedJoystickView_sliderHeight, width);
                borderPaint.setColor(borderColor);
                silderPaint.setColor(sliderColor);
            }
        }
        setOnTouchListener(this);
        border = new RectF(0, 0, width, height);
        availableStart = sliderHeight / 2;
        availableEnd = height - sliderHeight / 2;
        slider = new RectF((width - sliderWidth) / 2, 0, width - (width - sliderWidth) / 2, 0);

        rangeWidth = availableEnd - availableStart;
        yOffSet = availableStart + rangeWidth / 2;
        positionAnimator = ValueAnimator.ofFloat(1);
        positionAnimator.addUpdateListener(animation -> {
            Float aFloat = (Float) animation.getAnimatedValue();
            float center = availableStart + rangeWidth / 2;
            move(yOffSet + (center - yOffSet) * aFloat);
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(getActualSpec(widthMeasureSpec, true), getActualSpec(heightMeasureSpec, false));
    }


    public int getActualSpec(int spec, boolean width) {
        int mode = MeasureSpec.getMode(spec);
        int len = MeasureSpec.getSize(spec);
        if (mode == MeasureSpec.AT_MOST) {
            len = (int) (width ? this.width : this.height);
        }

        return MeasureSpec.makeMeasureSpec(len, mode);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawRect(border, borderPaint);
        // 将yOffSet复制到当前栈内，使用局部变量线程私有 ，防止计算过程更新导致矩形变形
        final float yOffSet = this.yOffSet;
        slider.top = yOffSet - sliderHeight / 2;
        slider.bottom = yOffSet + sliderHeight / 2;
        canvas.drawRect(slider, silderPaint);
    }

    public void setOnValueChangeListener(OnValueChangeListener onValueChangeListener) {
        this.onValueChangeListener = onValueChangeListener;
    }

    public void setOnValueResetListener(OnValueResetListener onValueResetListener) {
        this.onValueResetListener = onValueResetListener;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        float evx = event.getX(), evy = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //圆外按压不生效
                if (evx < 0 || evx > width || evy < 0 || evy > height) {
                    break;
                }
            case MotionEvent.ACTION_MOVE:
                if (move(evy) && onValueChangeListener != null) {
                    onValueChangeListener.onchange(value);
                }
                positionAnimator.cancel();
                break;
            case MotionEvent.ACTION_UP:
                positionAnimator.setDuration(100);
                positionAnimator.start();
                if (onValueResetListener != null) {
                    onValueResetListener.onReset();
                }
                break;
        }
        return true;
    }

    private boolean move(float evy) {
        // 上下限位
        if (evy < availableStart) {
            evy = availableStart;
        }
        if (evy > availableEnd) {
            evy = availableEnd;
        }

        final int value = (int) ((availableEnd - evy) * 100 / rangeWidth);
        if (value == this.value) {
            return false;
        }
        this.value = value;
        this.yOffSet = evy;

        invalidate();
        return true;
    }

    public interface OnValueChangeListener {
        void onchange(int value);
    }

    public interface OnValueResetListener {
        void onReset();
    }


}
